package com.cs171.market.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cs171.market.Repository.GoodRepository;
import com.cs171.market.entity.*;
import com.cs171.market.mapper.AttributeMapper;
import com.cs171.market.mapper.GoodMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * (Good)表控制层
 *
 * @author yangyifei
 * @since 2020-05-01 16:34:03
 */
@RestController
// @Api(value="/test", tags="JPA分组")
public class GoodController {
    /**
     * 服务对象
     */
    @Autowired
    private GoodRepository repository;
    @Autowired
    private GoodMapper goodMapper;
    @Autowired
    private AttributeMapper attributeMapper;
    @CrossOrigin

    /**
     * 1.查询多条商品数据
     * @return 多条数据
     */
    @GetMapping("/header/bestSelling")
    public Object selectAll() {
        System.out.println(repository.findAll());
        return JSON.toJSON(repository.findAll()) ;
    }

    /**
     * 2.查询单条商品数据
     * @return 单条数据
     */
    @GetMapping("/header/{id}")
    public Good selectOne(@PathVariable("id")Integer id) {
        System.out.println(repository.findById(id).orElse(null));
        return repository.findById(id).orElse(null);
    }

    @GetMapping("/header/select")
    public Object headerJson(){
        JSONArray bsSeafood = (JSONArray) JSON.toJSON(repository.getHeaderJsonAboutGoods("bestSelling","海鲜"));
        JSONObject bsSeafoodJson = new JSONObject();
        bsSeafoodJson.put("items", bsSeafood);
        bsSeafoodJson.put("category", "海鲜");

        JSONArray bsFruit = (JSONArray) JSON.toJSON(repository.getHeaderJsonAboutGoods("bestSelling","水果"));
        JSONArray bsVegetable = (JSONArray) JSON.toJSON(repository.getHeaderJsonAboutGoods("bestSelling","蔬菜"));
        JSONObject bsFruitJson = new JSONObject();
        bsFruit.addAll(bsVegetable);
        bsFruitJson.put("items", bsFruit);
        bsFruitJson.put("category", "果蔬");

        JSONArray bestSellingArray = new JSONArray();
        bestSellingArray.add(bsSeafoodJson);
        bestSellingArray.add(bsFruitJson);

        JSONArray seSeafood = (JSONArray) JSON.toJSON(repository.getHeaderJsonAboutGoods("select","海鲜"));
        JSONObject seSeafoodJson = new JSONObject();
        seSeafoodJson.put("items", seSeafood);
        seSeafoodJson.put("category", "海鲜");

        JSONArray seFruit = (JSONArray) JSON.toJSON(repository.getHeaderJsonAboutGoods("select","水果"));
        JSONArray seVegetable = (JSONArray) JSON.toJSON(repository.getHeaderJsonAboutGoods("select","蔬菜"));
        JSONObject seFruitJson = new JSONObject();
        bsFruit.addAll(seVegetable);
        seFruitJson.put("items", seFruit);
        seFruitJson.put("category", "果蔬");

        JSONArray selectArray = new JSONArray();
        selectArray.add(seSeafoodJson);
        selectArray.add(seFruitJson);

        JSONObject dataJson = new JSONObject();
        dataJson.put("bestSelling", bestSellingArray);
        dataJson.put("selling", selectArray);

        JSONObject headerJson = new JSONObject();
        headerJson.put("success","true");
        headerJson.put("data", dataJson);
        return headerJson;
    }

    @GetMapping("/goods")
    public Object goodListSearch(@RequestParam(value = "query", required = false) String query, @RequestParam(value = "pagenum",defaultValue = "1") Integer pagenum,
                                 @RequestParam(value = "pagesize", defaultValue = "1")Integer pagesize)
    {

        Integer success = 200;
        JSONObject jsonObject = new JSONObject();
        JSONObject metaObject = new JSONObject();
        PageHelper.startPage(pagenum,pagesize);
        JSONArray goodList = new JSONArray();
        if (query==null)
        {
            goodList =  (JSONArray) JSON.toJSON(goodMapper.getAllGoodList());
        }
        else
        {
            goodList = (JSONArray) JSON.toJSON(goodMapper.searchGoodList(query));
        }

        String count = goodMapper.countGood();
        JSONObject goods = new JSONObject();
        goods.put("goods", goodList);
        JSONObject data = new JSONObject();
        data.put("total", count);
        data.put("pagenum",pagenum);
        data.put("goods", goods);
        metaObject.put("msg","获取成功");
        metaObject.put("status", success);
        jsonObject.put("data", data);
        jsonObject.put("meta", metaObject);
        return jsonObject;
    }

    @PostMapping("/goods")
    public Object addGood(@RequestBody GoodModel goodModel)
    {
        System.out.println(goodModel);
        Integer success = 200;
        JSONObject jsonObject = new JSONObject();
        JSONObject metaObject = new JSONObject();
        Integer cat_id = Integer.valueOf(goodModel.getGoods_cat().split(",")[goodModel.getGoods_cat().split(",").length-1]);


        String allpics = "";
        for (Pic pic : goodModel.getPics())
        {
            allpics += pic.getPic()+",";
        }
        Integer time  = (int) (System.currentTimeMillis()/1000);


        goodMapper.addGoodAll(goodModel.getGoods_name(), cat_id, goodModel.getGoods_price(), goodModel.getGoods_number(), goodModel.getGoods_weight(), goodModel.getGoods_introduce(), allpics, time);

        if (goodModel.getAttrs().size()!=0)
        {
            for (AttributeEasy attr : goodModel.getAttrs())
            {
                if (attributeMapper.getSelById(attr.getAttr_id()).equals("only"))
                    attributeMapper.changeSelById(attr.getAttr_id());
                String oldVals = attributeMapper.getValsById(attr.getAttr_id());
                String newVals = oldVals + " " + attr.getAttr_value();
                attributeMapper.setValsById(attr.getAttr_id(),newVals);
            }
        }
        JSONObject data = (JSONObject) JSON.toJSON(goodMapper.responsToAdd(goodMapper.getNewGoodId()));
        List<Attribute> attributeList = new ArrayList<>();
        if (goodModel.getAttrs().size()!=0)
        {
            for (AttributeEasy attr : goodModel.getAttrs())
            {
                Attribute attribute = attributeMapper.getAttributeByIdForGood(attr.getAttr_id());
                attributeList.add(attribute);
            }
        }
        data.put("attrs",attributeList);
        metaObject.put("msg","创建商品成功");
        metaObject.put("status", success);
        jsonObject.put("data",data);
        jsonObject.put("meta", metaObject);
        return jsonObject;

    }

    @GetMapping("goods/{id}")
    public Object getGoodById(@PathVariable("id") Integer id)
    {
        Integer success = 200;
        JSONObject jsonObject = new JSONObject();
        JSONObject metaObject = new JSONObject();
        Good good = goodMapper.getGoodById(id);
        metaObject.put("msg","查询商品成功");
        metaObject.put("status", success);
        jsonObject.put("data",good);
        jsonObject.put("meta", metaObject);
        return jsonObject;
    }

    @PutMapping("goods/{id}")
    public Object updateGoodById(@PathVariable("id")Integer id,@RequestParam("goods_name")String name,
                                 @RequestParam("goods_price") Integer price, @RequestParam("goods_number")Integer number,
                                 @RequestParam("goods_weight") Integer weight)
    {
        Integer success = 200;
        JSONObject jsonObject = new JSONObject();
        JSONObject metaObject = new JSONObject();
        goodMapper.updateGood(id, name, price, number, weight);
        Good good = goodMapper.getGoodById(id);
        metaObject.put("msg","修改商品成功");
        metaObject.put("status", success);
        jsonObject.put("data",good);
        jsonObject.put("meta", metaObject);
        return jsonObject;
    }

    @DeleteMapping("goods/{id}")
    public Object deleteGood(@PathVariable("id") Integer id)
    {
        Integer success = 200;
        JSONObject jsonObject = new JSONObject();
        JSONObject metaObject = new JSONObject();
        goodMapper.deleteGood(id);
        metaObject.put("msg","删除成功");
        metaObject.put("status",success);
        jsonObject.put("data","null");
        jsonObject.put("meta",metaObject);
        return jsonObject;
    }



}